<template>
  <div class="task-detail">
    <div class="info-view">
      <div class="info-view-header">
        <TaskChatTab v-model="detailActiveTab" :data="detailTabList"></TaskChatTab>
        <el-popover placement="bottom" trigger="click">
          <div class="pointer" v-for="(status, index) in statusList" :key="index" @click="handleUpdate(status)">
            {{ status }}
          </div>
          <template #reference>
            <el-icon size="16"><MoreFilled /></el-icon>
          </template>
        </el-popover>
      </div>
      <div class="task-info">
        <template v-if="detailActiveTab === 0">
          <div class="info-item task-info-detail">
            <div class="task-info-detail-title">
              <span>#{{ props.task.taskCode }}</span>
              <span>{{ props.task.taskTitle }}</span>
            </div>
            <RichTextViewer :view-html="props.task.taskDetail"></RichTextViewer>
          </div>
          <div class="info-item">
            <el-descriptions :column="4" border>
              <el-descriptions-item label="优先级" :span="2" width="80px">
                <span :style="priorityColor(props.task.taskPriority)" style="padding: 5px 10px">
                  {{ dict.translate('task_priority', props.task.taskPriority) }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="任务类型" :span="2" width="80px">
                <span :style="taskTypeColor(props.task.taskProp)" style="padding: 5px 10px">
                  {{ dict.translate('task_type', props.task.taskProp) }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="开始日期" :span="2" width="120px">
                {{ props.task.planBegintime }}
              </el-descriptions-item>
              <el-descriptions-item label="当前进度" :span="2">
                <el-progress
                  :percentage="props.task.completePercent"
                  :color="formatterColor(props.task.currentStatus)"></el-progress>
              </el-descriptions-item>
              <el-descriptions-item label="计划日期" :span="2">
                {{ props.task.planEndtime }}
              </el-descriptions-item>
              <el-descriptions-item label="负责人" :span="2" width="80px">
                {{ props.task.taskUserName }}
              </el-descriptions-item>
              <el-descriptions-item label="实际完成日期" :span="2" width="120px">
                {{ props.task.currentEndTime }}
              </el-descriptions-item>

              <el-descriptions-item label="协助人" :span="2">
                {{ props.task.taskAssistName }}
              </el-descriptions-item>
              <el-descriptions-item label="预计用时" :span="2">{{ props.task.planCostHour }} 小时</el-descriptions-item>
              <el-descriptions-item label="管理人" :span="2">
                {{ props.task.taskLeaderName }}
              </el-descriptions-item>
              <el-descriptions-item label="实际用时" :span="2">
                {{ props.task.currentCostHour }} 小时
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <div class="info-item">
            <el-descriptions :column="4" border direction="vertical">
              <el-descriptions-item label="子任务" :span="2" width="80px">
                <div v-for="(item, index) in props.task.children" :key="index">
                  <span style="color: var(--elp-color-primary-light-3); cursor: pointer" @click="viewChildTask(item)">
                    {{ `#${item.taskCode} ` }}
                  </span>
                  {{ item.taskTitle }}
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </template>
        <div v-if="detailActiveTab === 1">
          <!-- v-if="task.taskAssistid === userInfo.userId || task.taskUserId === userInfo.userId" -->
          <div
            class="info-item"
            v-show="
              task.currentStatus !== 4 &&
              !props.hoursCheck &&
              (task.taskAssistid === userInfo.userId || task.taskUserId === userInfo.userId)
            ">
            <div class="submit-btn-wrap">
              <div class="info-title">
                <span>工时登记</span>
                <span v-if="task.taskProp === 5">(兼职任务工时为0，独立统计)</span>
              </div>
              <el-button type="primary" @click="submitFunc" :loading="isLoading" class="submit-btn">提交</el-button>
            </div>
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-form-item label="日期：" prop="selectDay">
                    <el-date-picker
                      :style="{ width: '100%' }"
                      v-model="form.selectDay"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      disabled
                      placeholder="日期" />
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="工时登记：" prop="wrHours">
                    <el-input v-if="task.taskProp !== 5" v-model="form.wrHours" type="number" placeholder="请输入">
                      <template #suffix>h</template>
                    </el-input>
                    <el-input v-else v-model="form.wrHours" type="number" disabled>
                      <template #suffix>h</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-form-item label="工时分类：" prop="workType">
                    <el-select v-model="form.workType" placeholder="请选择" clearable>
                      <el-option
                        v-for="(item, index) in dict.dictMap['work_type']"
                        :key="index"
                        :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="完成度：" prop="completePercent">
                    <el-input
                      v-model="form.completePercent"
                      type="number"
                      @input="(val) => onInput(val)"
                      placeholder="请输入">
                      <template #suffix>%</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" v-if="props.task.delayFlag === 1">
                <el-col :span="10">
                  <el-form-item label="延期原因：" required :error="customError">
                    <el-select
                      v-model="reasonForExtensions"
                      @blur="checkCustomValid"
                      placeholder="请选择"
                      multiple
                      filterable
                      :reserve-keyword="true"
                      @change="reasonForExtension">
                      <el-option
                        v-for="(item, index) in dict.dictMap['task_info_delay_reason']"
                        :key="index"
                        :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10" v-if="isRemark">
                  <el-form-item label="备注：">
                    <el-input placeholder="请输入" v-model="remarks"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="20">
                  <el-form-item label="说明：" prop="remark">
                    <el-input v-model="form.remark" maxlength="125" :rows="2" type="textarea" placeholder="请输入" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="info-item">
            <div class="info-title">工时明细</div>
            <el-table :data="task.workingRecordList" :height="275">
              <el-table-column label="登记人" prop="registrants"></el-table-column>
              <el-table-column label="日期" prop="selectDay" align="center">
                <template v-slot="{ row }">
                  <span>{{ dayjs(row.selectDay).format('YYYY-MM-DD') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态" prop="wrStatus" align="center">
                <template v-slot="{ row }">
                  <span>{{ dict.translate('work_status', row.wrStatus) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="分类" prop="workType" align="center">
                <template v-slot="{ row }">
                  <span>{{ dict.translate('work_type', row.workType) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="登记工时(小时)" prop="wrHours" align="center">
                <template v-slot="{ row }">
                  <span>{{ row.wrHours }}小时</span>
                </template>
              </el-table-column>
              <el-table-column label="更新进度(%)" prop="completePercent" align="center">
                <template v-slot="{ row }">
                  <span>{{ row.completePercent }}%</span>
                </template>
              </el-table-column>
              <el-table-column label="登记时间" prop="createdTime" align="center"></el-table-column>
            </el-table>
          </div>
        </div>
        <div v-if="detailActiveTab === 2" class="info-item task-info-fill">
          <Dynamic :data="task.taskChangeRecordList" :projectMemberList="projectMemberList"></Dynamic>
        </div>
      </div>
    </div>
    <TaskChatDialog
      body-class-name="dialog-child-custom"
      :model-value="childTaskVisible"
      :title="taskDialogTitle"
      width="1200px"
      append-to-body
      showMessage
      allow-operations
      @close="handleDetailClose">
      <TaskDetail :task="childTask"></TaskDetail>
    </TaskChatDialog>
    <div v-if="props.showMessage" class="message-view">
      <div class="message-view-header">
        <TaskChatTab v-model="messageActiveTab" :data="messageTabList"></TaskChatTab>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { formatterColor, priorityColor, taskTypeColor } from '@/utils/task-utils.js'
import { MoreFilled } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { addWorkHourRecord } from '@/assets/api/work-hour-record'
import { useDictionary } from '@/use/use-dictionary'
import { getProjectMember } from '@/assets/api/project'
import useUser from '@/store/user'
import { getTaskDetail } from '@/assets/api/task'

const emit = defineEmits(['refresh', 'dialogClick'])
const userStore = useUser()
let userInfo = userStore.userInfo

const dict = useDictionary([
  'work_type',
  'work_status',
  'task_priority',
  'task_type',
  'work_time',
  'task_info_delay_reason',
])
const props = defineProps({
  task: Object,
  showMessage: Boolean,
  allowOperations: Boolean,
  hoursCheck: Boolean,
})

// timeJudgment(
//   dict.getListByType('work_time'),
//   dict.translate('work_time', dayjs(props.task.planEndtime).format('HH:mm:ss'))
// )
const detailTabList = [
  { label: '基本', name: 0 },
  { label: '工时', name: 1 },
  { label: '动态', name: 2 },
]
const messageTabList = [{ label: '聊天', name: 0 }]

const detailActiveTab = ref(0)
const messageActiveTab = ref(0)
const isLoading = ref(false)

let statusList = []
if (props.allowOperations) {
  // statusList = ['进入群组']
  statusList = []
} else if (props.task.currentStatus.toString() === '1') {
  // statusList = ['任务领取', '进入项目', '进入群组']
  statusList = ['任务领取', '进入项目']
} else {
  // statusList = ['进入项目', '进入群组']
  statusList = ['进入项目']
}

const rules = {
  selectDay: [{ required: true, message: '请选择日期', trigger: 'change' }],
  workType: [{ required: true, message: '请选择分类', trigger: 'change' }],
  wrHours: [{ required: true, message: '请登记工时', trigger: 'blur' }],
  completePercent: [{ required: true, message: '请输入完成度', trigger: 'blur' }],
}

// 延期选择
const remarks = ref('')
const fillInTheReasonForDelay = ref(null)
const isRemark = ref(false)
const reasonForExtensions = ref([])
const customError = ref('')

function handleUpdate(status) {
  switch (status) {
    case '任务领取':
      handleReceiveTask()
      break
    case '进入项目':
      handleGoProject()
      break
    case '进入群组':
      emit('dialogClick', props.task)
  }
}

function handleReceiveTask() {
  emit('receiveTask', JSON.parse(JSON.stringify(props.task)))
}

function handleGoProject() {
  emit('goProject', JSON.parse(JSON.stringify(props.task)))
}

const formRef = ref()
// const form = reactive(JSON.parse(JSON.stringify(props.task)))
const form = ref({
  selectDay: dayjs().format('YYYY-MM-DD'),
  wrHours: 0,
})

const workingRecord = ref()

resetWorkingRecord()

function resetWorkingRecord() {
  workingRecord.value = {
    selectDay: dayjs().format('YYYY-MM-DD'),
    workType: null,
    wrHours: 0,
    taskId: form.value.taskId,
    completePercent: null,
    taskType: 1,
  }
}

const submitShow = computed(() => {
  return form.value.workingRecordList.some((i) => !i.registrants)
})

function handleAddWorkHours() {
  form.value.workingRecordList.push(workingRecord.value)
}

function submit() {
  formRef.value.validate((valid) => {
    if (valid) {
      addWorkHourRecord(workingRecord.value).then((res) => {
        if (res.code === 200) {
          ElMessage.success('登记成功')
        }
      })
    } else {
      ElMessage({
        message: '请填写内容',
        type: 'warning',
      })
    }
  })
}

function submitFunc() {
  formRef.value.validate((valid) => {
    if (valid) {
      if (props.task.delayFlag === 1 && checkCustomValid()) {
        ElMessage({
          message: '请填写内容',
          type: 'warning',
        })
        return
      }
      if (isRemark.value) {
        fillInTheReasonForDelay.value.map((item) => {
          if (item.reasonId === '7') {
            item.reasonRemark = remarks.value
          }
        })
      }
      form.value = {
        ...form.value,
        taskId: props.task.taskId,
        taskType: 1,
        tcTaskInfoDelays: fillInTheReasonForDelay.value,
      }
      if (form.value.wrHours > parseInt(dict.getCode('work_time', '5'))) {
        ElMessage.warning(`登记工时不可超过${dict.getCode('work_time', '5')}小时`)
        return
      }
      isLoading.value = true
      addWorkHourRecord(form.value).then((res) => {
        if (res.code === 200) {
          ElMessage.success('登记成功')
          emit('refresh', props.task.taskId)
          formRef.value.resetFields()
          isRemark.value = false
          remarks.value = ''
          reasonForExtensions.value = []
        } else {
          ElMessage.error(res.msg)
        }
        isLoading.value = false
      })
    } else {
      ElMessage({
        message: '请填写内容',
        type: 'warning',
      })
    }
  })
}

// 输入数字校验
function onInput(val) {
  let num = val.replace(/[^\d]/g, '')
  if (num > 100) {
    form.value.completePercent = 100
  } else if (num < 0) {
    form.value.completePercent = 0
  } else {
    form.value.completePercent = num
  }
}

getProjectMemberData()

const projectMemberList = ref([])
function getProjectMemberData() {
  //查询项目成员
  getProjectMember({ projectId: props.task.projectId }).then((res) => {
    if (res.code === 200) {
      projectMemberList.value = res.rows
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const childTaskVisible = ref(false)
const childTask = ref({})

const taskDialogTitle = computed(() => {
  if (childTask.value.taskTitle) {
    const { projectName, itemName, taskTitle, taskCode } = childTask.value
    return `${projectName}/${itemName}/${taskTitle}-#${taskCode}`
  }
  return ''
})
function viewChildTask(task) {
  getTaskDetail(task.taskId).then((res) => {
    if (res.code === 200) {
      childTask.value = res.data
      childTaskVisible.value = true
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 非表单校验
function checkCustomValid() {
  if (reasonForExtensions.value.length === 0) {
    customError.value = '请选择延期原因'
    return true
  } else {
    customError.value = ''
    return false
  }
}

function updateReasonForDelay(reasonIds) {
  fillInTheReasonForDelay.value = reasonIds.map((reasonId) => ({ reasonId }))
  isRemark.value = reasonIds.includes('7')
}

function reasonForExtension() {
  const reasonIds = reasonForExtensions.value.map((obj) => obj[Object.keys(obj)[0]])
  updateReasonForDelay(reasonIds)
}

if (props.task.delayFlag === 1 && props.task.tcTaskInfoDelays.length > 0) {
  props.task.tcTaskInfoDelays.forEach((item) => {
    if (userInfo.userId === item.userId) {
      reasonForExtensions.value.push(item.reasonId.toString())
      const reasonIds = reasonForExtensions.value.map((obj) => obj[Object.keys(obj)[0]])
      updateReasonForDelay(reasonIds)
      if (item.reasonId === 7) {
        remarks.value = item.reasonRemark
        isRemark.value = true
      }
    }
  })
}

function handleDetailClose() {
  childTaskVisible.value = false
  childTask.value = {}
}
</script>

<style scoped lang="scss">
.task-detail {
  @include use-flex(normal, space-between);
  height: 650px;
  .info-view {
    flex: 1;
    height: 100%;
    overflow: hidden;
    .info-view-header {
      padding: 0 0 20px;
      @include use-flex(center, space-between);
      .elp-icon {
        cursor: pointer;
      }
    }
    .task-info {
      overflow: auto;
      height: calc(100% - 41px);
      :deep(.elp-image-viewer__mask) {
        background-color: var(--elp-bg-color);
        opacity: 1;
      }
      .info-item {
        padding: 10px;
        border-radius: 8px;
        background-color: var(--elp-bg-color);
        & + .info-item {
          margin-top: 10px;
        }
        &-child-title {
          font-weight: 700;
          color: #606266;
        }
      }
      .task-info-detail {
        min-height: 120px;
        .task-info-detail-title {
          font-size: 18px;
          span:first-child {
            margin-right: 5px;
          }
        }
      }
      .task-info-fill {
        height: 100%;
        overflow: auto;
      }
    }
    .register-working-hours {
      @include use-flex(center);
      color: var(--elp-color-primary-light-3);
      cursor: pointer;
      float: right;
      margin-bottom: 5px;
      span {
        @include use-flex(center);
        padding: 0 5px;
        & + span {
          border-left: var(--elp-border);
        }
      }
      .elp-icon,
      .svg-icon {
        margin-right: 5px;
      }
    }
    :deep(.elp-descriptions) {
      .elp-descriptions__cell {
        border: none;
      }
      .elp-descriptions__label {
        background: none;
      }
    }
  }

  .info-title {
    padding: 10px;
    color: var(--elp-color-primary-light-3);
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 4px;
  }
  .message-view {
    width: 40%;
    height: 100%;
    margin-left: 10px;
    .message-view-header {
      padding: 0 10px 20px;
    }
  }
}

.elp-select,
.elp-input {
  width: 100%;
}

.submit-btn-wrap {
  // text-align: right;
  @include use-flex(center, space-between);
  .submit-btn {
    padding: 0 40px;
  }
}

.pointer {
  cursor: pointer;
  margin: 5px;
}

:deep(input)::-webkit-outer-spin-button,
:deep(input)::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
:deep(input[type='number']) {
  -moz-appearance: textfield !important;
}
</style>
